package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        List<SetmealDish> collect = dishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(collect);
    }

    @Override
    @Transactional
    public void updateWithDish(SetmealDto setmealDto) {
        Setmeal setmeal=new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);
        LambdaQueryWrapper<Setmeal> qw=new LambdaQueryWrapper<>();
        this.updateById(setmeal);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        LambdaQueryWrapper<SetmealDish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getId()!=null,SetmealDish::getSetmealId,setmeal.getId());
        setmealDishes.remove(lqw);
        setmealDishes.addAll(setmealDishes);

    }

    @Override
    public void deleteWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getStatus,1).in(Setmeal::getId,ids);
        int count = this.count(lqw);
        if(count>0){
          throw  new CustomException("该套餐还未停售,不能删除");
        }
        this.removeByIds(ids);
        LambdaQueryWrapper<SetmealDish> qw=new LambdaQueryWrapper<>();
        qw.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(qw);
    }
}
